package com.copd.service.impl;

import com.copd.entity.User;
import com.copd.mapper.UserMapper;
import com.copd.service.UserService;
import com.copd.util.PasswordUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public void register(User user) {
        // 检查用户名是否已存在
        User existingUser = userMapper.findByUsername(user.getUsername());
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 检查联系方式是否已存在
        if (user.getContactInfo() != null && isContactInfoExists(user.getContactInfo())) {
            throw new RuntimeException("联系方式已被使用");
        }

        // 如果是医生角色，验证医生特有字段
        if ("doctor".equalsIgnoreCase(user.getRole())) {
            if (user.getTitle() == null || user.getTitle().trim().isEmpty()) {
                throw new RuntimeException("医生职称不能为空");
            }
            if (user.getDepartment() == null || user.getDepartment().trim().isEmpty()) {
                throw new RuntimeException("医生科室不能为空");
            }
            if (user.getYearsOfExperience() == null || user.getYearsOfExperience() < 0) {
                throw new RuntimeException("从业年限不能为空且必须大于等于0");
            }
            if (user.getCertification() == null || user.getCertification().trim().isEmpty()) {
                throw new RuntimeException("资质认证不能为空");
            }
        }

        // 生成随机userId
        int userId;
        do {
            userId = User.generateRandomUserId();
        } while (userMapper.selectById(userId) != null);  // 确保userId不重复

        // 设置用户信息
        user.setUserId(userId);
        
        // 处理密码 - 前端已经使用SHA-256加密
        String password = user.getPassword();
        logger.debug("Password from frontend (SHA-256): {}", password);
        
        // 直接存储前端传来的SHA-256加密密码
        user.setPassword(password);
        logger.debug("Stored password: {}", user.getPassword());
        
        user.setCreateTime(LocalDateTime.now());

        // 插入用户
        try {
            userMapper.insert(user);
        } catch (Exception e) {
            throw new RuntimeException("用户注册失败: " + e.getMessage());
        }
    }

    @Override
    public boolean isUsernameExists(String username) {
        return userMapper.findByUsername(username) != null;
    }

    @Override
    public boolean isContactInfoExists(String contactInfo) {
        return userMapper.selectByContactInfo(contactInfo) != null;
    }

    @Override
    public boolean verifyPassword(String rawPassword, String encodedPassword) {
        logger.debug("Verifying password - Raw password hash length: {}", rawPassword != null ? rawPassword.length() : 0);
        logger.debug("Stored password hash length: {}", encodedPassword != null ? encodedPassword.length() : 0);
        
        // 使用 PasswordUtil 进行验证
        return PasswordUtil.matches(rawPassword, encodedPassword);
    }

    @Override
    public User login(String username, String password) {
        logger.debug("Attempting login for user: {}", username);
        logger.debug("Received password hash length: {}", password != null ? password.length() : 0);
        
        // 查找用户
        User user = userMapper.findByUsername(username);
        if (user == null) {
            logger.debug("User not found: {}", username);
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 记录密码信息
        logger.debug("Login attempt - Username: {}", username);
        logger.debug("Login attempt - Input password hash: {}", password);
        logger.debug("Login attempt - Stored password hash: {}", user.getPassword());
        
        // 验证密码 - 直接比较哈希值
        if (!password.equals(user.getPassword())) {
            logger.debug("Password verification failed for user: {}", username);
            throw new RuntimeException("用户名或密码错误");
        }
        
        logger.debug("Login successful for user: {}", username);
        return user;
    }
    
    @Override
    @Transactional
    public void updateUserInfo(User user) {
        logger.debug("Updating user info for userId: {}", user.getUserId());
        
        // 验证用户存在
        User existingUser = userMapper.selectById(user.getUserId());
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 如果更新了手机号，检查是否与其他用户的手机号冲突
        if (user.getContactInfo() != null && !user.getContactInfo().isEmpty()) {
            User userWithSameContact = userMapper.selectByContactInfo(user.getContactInfo());
            if (userWithSameContact != null && !userWithSameContact.getUserId().equals(user.getUserId())) {
                throw new RuntimeException("该手机号已被其他用户使用");
            }
        }
        
        int result = userMapper.updateUserInfo(user);
        if (result <= 0) {
            throw new RuntimeException("更新用户信息失败");
        }
        
        logger.debug("User info updated successfully");
    }
} 